<template>
    <rx-dialog @handOk="handleSubmit" @cancel="cancel">
        <rx-layout>
            <div slot="center">
                <a-form :form="form" style="padding: 10px;" layout="vertical">
                    <a-form-item style="display:none">
                        <a-input v-decorator="['id']"/>
                    </a-form-item>
                    <a-row :gutter="24">
                        <a-col :span="12">
                            <a-form-item  :label="i18n('form.formulaName','公式名称')">
                                <a-input :placeholder="i18n('form.name','名称')" v-decorator="['name', {rules: [{required: true, message: i18n('form.name','名称','input')}]}]"/>
                            </a-form-item>
                        </a-col>
                        <a-col :span="12">
                            <a-form-item  :label="i18n('form.businessMo','业务模型')" class="rxbox">
                                <rx-input-button ref="inputButton"
                                    width="80%" @click="openBoDef" @change="changeBoDef"
                                    v-decorator="['boDefId',{rules:[{required:true,message:i18n('content.isNullMsg','不能为空!')}]}]"
                                ></rx-input-button>
                            </a-form-item>
                        </a-col>

                        <a-col :span="12">
                            <a-form-item  :label="i18n('form.classificationSelection','分类选择')">
                                <rx-category-select cat-key="FORM" :isGrant="true" v-if="isShowManageTree"
                                                    :isAdmin="isManageToTree"
                                                    v-decorator="['treeId', {rules: [{required: true, message: i18n('content.classification','分类','input')}]}]"></rx-category-select>
                                <a-input v-else style="display:none;" v-decorator="['treeId']"/>
                            </a-form-item>
                        </a-col>
                        <a-col :span="12">
                            <a-form-item :label="i18n('form.enabled','启用')">
                                <div style="min-height: 32px">
                                    <a-radio-group :options="enabledtions" v-decorator="['enabled', {initialValue:'YES'}]"/>
                                </div>
                            </a-form-item>
                        </a-col>

                        <a-col :span="12">
                            <a-form-item :label="i18n('form.timingOfAction','动作时机')">
                                <a-checkbox-group :options="actionOptions" v-decorator="['action', {rules: [{required: true,message:i18n('content.isNullMsg','不能为空!')}]}]"/>
                            </a-form-item>
                        </a-col>
                        <a-col :span="12">
                            <a-form-item :label="i18n('form.debugMode','调试模式')">
                                <a-radio-group :options="isTestOptions" v-decorator="['isTest', {initialValue:'NO'}]"/>
                            </a-form-item>
                        </a-col>

                        <a-col :span="24">
                            <a-form-item :label="$ti18('rxList.config','配置')" class="labelText">
                                <div class="table-operator">
                                    <a-button-group>
                                        <a-button @click="addFormula" type="primary">
                                            {{ $ti18('rxList.newBtn', '新增') }}
                                        </a-button>
                                        <a-button @click="removeFormula">{{ $ti18('rxList.delBtn', '删除') }}</a-button>
                                        <a-button @click="upRow">{{ i18n('button.upward', '向上') }}</a-button>
                                        <a-button @click="downRow">{{ i18n('button.downward', '向下') }}</a-button>
                                    </a-button-group>

                                </div>

                                <rx-grid
                                    ref="table"
                                    :dataSource="fields"
                                    :allowRowSelect="true"
                                    :multiSelect="true"
                                    :showPage="false"
                                    :columns="columns"
                                    style="height: 180px;padding: 0;"
                                >
                                    <span slot="name" slot-scope="{text,record,index}">
                                        <a-select
                                            :value="record.name"
                                            @change="nameChange($event,record)"
                                            :options="nameData"/>
                                    </span>
                                    <span slot="setting" slot-scope="{text,record,index}">
                                        <a-button type="link" @click="editFormula(record)" style="padding: 0 ">
                                            {{ $ti18('rxList.config', '配置') }}
                                        </a-button>
                                    </span>

                                    <span slot="opDescp" slot-scope="{text,record,index,blur}">
                                        <a-input v-model="record.opDescp" @blur="blur(index,'opDescp',text,record)"/>
                                    </span>
                                </rx-grid>
                            </a-form-item>
                        </a-col>

                        <a-col :span="24">
                            <a-form-item :label="i18n('form.formulaDescription','公式描述')">
                                <a-textarea
                                    :placeholder="i18n('form.formulaDescription','公式描述')"
                                    v-decorator="['descp', {rules: [{required: false, message: i18n('form.name','名称', 'input')}]}]"
                                />
                            </a-form-item>
                        </a-col>
                    </a-row>
                </a-form>

            </div>
        </rx-layout>
    </rx-dialog>
</template>
<script>
import FormTableFormulaApi from '@/api/form/core/formTableFormula'
import FormBoDefApi from '@/api/form/bo/formBoDef'
import {BaseForm, Dialog, RxDialog, RxInputButton, RxGrid, Util} from '@lowcode/jpaas-common-lib';
import FormTableFormulaDataAdd from "./TableForrmula/FormTableFormulaDataAdd.vue";

export default {
    name: 'FormTableFormulaEdit',
    mixins: [BaseForm],
    components: {
        RxDialog,
        RxInputButton,
        RxGrid
    },
    computed: {
        table() {
            return this.$refs.table;
        },
    },
    data() {
        return {
            fields: [],
            columns: [
                {
                    title: this.$ti18('rxList.index', '序号'),
                    type: 'indexColumn',
                    width: 80,
                    dataIndex: 'serial',
                    scopedSlots: {customRender: 'serial'}
                },
                {
                    title: this.i18n('form.entity', '实体'),
                    dataIndex: 'name',
                    width: 120,
                    scopedSlots: {customRender: 'name'}
                },
                {
                    title: this.i18n('form.config', '配置'),
                    dataIndex: 'setting',
                    width: 120,
                    scopedSlots: {customRender: 'setting'}
                },
                {
                    title: this.i18n('form.executiveDescription', '执行描述'),
                    dataIndex: 'opDescp',
                    allowCellEdit: true,
                    width: 120,
                    scopedSlots: {customRender: 'opDescp'}
                },

            ],
            nameData: [],
            actionOptions: [
                {label: this.$ti18('rxList.newBtn', '新建'), value: 'new'},
                {label: this.$ti18('rxList.update', '更新'), value: 'upd'},
                {label: this.$ti18('rxList.delBtn', '删除'), value: 'del'}
            ],
            isTestOptions: [
                {label: this.i18n('isTestMap.yes', '是'), value: 'YES'},
                {label: this.i18n('isTestMap.no', '否'), value: 'NO'}
            ],
            enabledtions: [
                {label: this.i18n('isTestMap.yes', '是'), value: 'YES'},
                {label: this.i18n('isTestMap.no', '否'), value: 'NO'}
            ],
            complexJson: {
                main: {
                    boDefId: {text: "boDefName", value: "boDefId"}
                }
            }
        }
    },
    created() {
        this.isUserManager(this.$route.query.appId);
    },
    methods: {
        i18n(name, text, key) {
            return this.$ti18(name, text, "formTableFormula", key);
        },
        onload_(values) {
            if (values) {
                this.loadBoDef(JSON.parse(values.boDefId).value);
                values.action = values.action.split(",");
                if (values.fillConf) {
                    this.fields = JSON.parse(values.fillConf);
                }
            }
        },
        get(id) {
            return FormTableFormulaApi.get(id);
        },
        save(values) {
            values.action = values.action.join(",");
            values.fillConf = JSON.stringify(this.table.getData());
            return FormTableFormulaApi.save(values);
        },
        openBoDef(vm) {
            let self = this , id = ''
            if(vm.value){
                let fn = new Function(`return ${vm.value}`)();
                id = fn['value']
            }
            Dialog.openBoDefDialog({
                curVm: this,
                widthHeight: ['1000px', '600px']
            }, function (data) {
                if(!id || (id !== data.id)){
                    self.fields = []
                    self.loadBoDef(data.id)
                    vm.setVal(data.id, data.name)
                }
            })
        },
        loadBoDef(boDefId) {
            FormBoDefApi.getBosByDefId(boDefId).then(res => {
                this.nameData = res.data;
            })
        },
        addFormula() {
            var boDefId = this.form.getFieldValue("boDefId");
            if (!boDefId) {
                this.$message.error(this.i18n('content.model', '请选择筛选业务对象模型！'));
                return;
            }
            this.table.addRow({});
        },
        removeFormula() {
            this.table.removeRows();
        },
        setInitRow(row,value){
            row.name = value ;
            let ary = this.nameData.filter(item => {
                return item.value == value;
            });
            if (ary && ary.length > 0) {
                row.comment = ary[0].label;
                row.isMain = ary[0].isMain;
                row.type = ary[0].type || "main" ;
            }
            row.settings = {} ;
        },
        nameChange(value, row) {
            if(!row.name){
                this.setInitRow(row,value)
                return ;
            }
            let self= this ;
            this.$confirm({
                content:this.i18n('form.changeTips','切换时配置会清空，您确定要这样做吗？'),
                cancelText:this.i18n('form.cancel','取消'),
                okText:this.i18n('form.ok','确定'),
                zIndex:99999,
                maskClosable:true,
                keyboard:true,
                centered:true,
                onOk(){
                    self.setInitRow(row,value)
                },
                onCancel(){}
            })
        },
        editFormula(record) {
            var boDefId = this.form.getFieldValue("boDefId");
            if (!boDefId) {
                this.$message.error(this.i18n('content.model', '请选择筛选业务对象模型！'));
                return;
            }
            if (!record.name) {
                this.$message.error(this.i18n('content.map', '请选择需要映射的实体！'));
                return;
            }
            var baseConf = {
                "curVm": this,
                component: FormTableFormulaDataAdd,
                title:(record.comment || '') + this.i18n('form.setMapping', '设置映射'),
                max:true,
                data: {
                    dataConf: record.settings,
                    //业务模型id
                    boDefId: JSON.parse(boDefId).value,
                    //实体名称
                    boName: record.name,
                    //来源表名
                    comment: record.comment,
                    //是否主表
                    isMain: record.isMain,
                    //实体类型
                    type: record.type
                }
            };
            Util.open(baseConf, function (action, data) {
                if (action != "ok") return;
                record.settings = data;
            });
        },
        upRow() {
            this.table.moveUp();
        },
        downRow() {
            this.table.moveDown();
        },
        changeBoDef(val) {
            if (!val) {
                this.fields = [];
            }
        }
    },

}
</script>
<style scoped>
form:not(.ant-form-vertical) :not(.ant-input-group-wrapper) >>> .ant-input-group {
    top: 4px !important;
}

.rxbox >>> .inputBtnBox {
    vertical-align: top;
}
</style>